# -*- coding: utf-8-*-
# 网易云音乐播放
import logging
import threading
import hashlib
import time
import subprocess
import sys
import os
import re
import random
from MusicBoxApi import api as NetEaseApi
import eyed3
from random import shuffle

reload(sys)
sys.setdefaultencoding('utf8')

#import cProfile, pstats, StringIO

SLUG = "netease_music"

def main():
    """
    main function
    """
    logger = logging.getLogger(__name__)

    logger.debug("Preparing to start netease music module")
    try:
        netease_wrapper = NetEaseWrapper()
    except Exception, e:
        logger.debug(e)
        logger.error("Couldn't connect to NetEase server", exc_info=True)
        sys.exit(0)

    logger.debug("Starting music mode")

    music_mode = MusicMode(netease_wrapper)
    music_mode.stop = False

    # 登录网易云音乐
    account = '15279120913'
    password = 'wjy1587958'
    report = False
    local_default = False

    if account == '' or password == '':
        logger.error('请先配置好账户信息再找我播放音乐')
        sys.exit(0)

    has_login = False
    home_dir = os.path.expandvars('$HOME')
    user_info = os.path.join(home_dir, 'userInfo')
    if not (os.path.exists(user_info)):
        logger.debug('稍等，正在为您登录网易云音乐')
        logger.debug
        res = music_mode.login(account, password, report)
        if res:
            logger.debug('登录成功')
            has_login = True
    else:
        music_mode.read_login_info(user_info, report)
        has_login = True

    if not has_login:
        logger.error('登录失败, 退出播放. 请检查配置, 稍后再试')
        sys.exit(0)

    music_mode.handleForever(play_type=1)  # 1: 用户歌单
    # music_mode.handleForever(play_type=0)  # 0: 推荐榜单
    logger.debug("Exiting music mode")

# The interesting part
class MusicMode(object):

    def __init__(self,netease_wrapper):
        self._logger = logging.getLogger(__name__)
        self.music = netease_wrapper
        self.search_mode = False
        self.to_listen = True
        self.to_report = False
        self.delegating = False

    def read_login_info(self, user_info, report=False):
        self.to_report = report
        self.music.read_login_info(user_info)

    def login(self, account, password, report=False):
        self.to_report = report
        return self.music.login(account, password)

    def handleForever(self, play_type=0, song_name=''):
        """
        进入音乐播放
        play_type - 0：播放推荐榜单；1：播放用户歌单
        """
        if song_name != '':
            self.music.update_playlist_by_type(2, song_name)
        else:
            self.music.update_playlist_by_type(play_type)
        self.music.start()

        while True:

            if self.music.is_stop:
                self._logger.info('Stop Netease music mode')
                return

class NetEaseWrapper(threading.Thread):

    def __init__(self):
        super(NetEaseWrapper, self).__init__()
        self.logger = logging.getLogger(__name__)
        self.cond = threading.Condition()
        self.netease = NetEaseApi.NetEase()
        self.userId = ""
        self.volume = 0.7
        self.song = None  # 正在播放的曲目信息
        self.idx = -1  # 正在播放的曲目序号
        self.random = False
        self.playlist = []
        self.is_pause = False
        self.is_stop = False

    def set_cond(self, cond):
        self.cond = cond

    def update_playlist_by_type(self, play_type, keyword=''):
        if play_type == 0:
            # 播放热门榜单音乐
            self.playlist = self.get_top_songlist()
        elif play_type == 1:
            # 播放用户歌单
            user_playlist = self.get_user_playlist()
            if user_playlist > 0:
                self.playlist = self.get_song_list_by_playlist_id(
                    user_playlist[0]['id'])
                if len(self.playlist) == 0:
                    logger.debug('用户歌单没有歌曲，改为播放推荐榜单')
                    self.playlist = self.get_top_songlist()
            else:
                logger.debug('用户歌单没有歌曲，改为播放推荐榜单')
                self.playlist = self.get_top_songlist()
        elif play_type == 2:
            # 搜索歌曲
            self.playlist = self.search_by_name(keyword)
        elif play_type == 3:
            self.playlist = self.get_local_songlist()

    def get_local_songlist(self):  # 本地音乐
        local_path = ''
        if 'local_path' in self.profile[SLUG]:
            local_path = self.profile[SLUG]['local_path']

        playlist = []
        for (dirpath, dirnames, filenames) in os.walk(local_path):
            # f.extend(filenames)
            for filename in filenames:
                try:
                    # only mp3 accept
                    if os.path.splitext(filename)[1] != ".mp3":
                        continue
                    # read mp3 properties and add to the playlist
                    mp3_path = dirpath + filename
                    audiofile = eyed3.load(mp3_path)
                    music_info = {}
                    if audiofile.tag:
                        if audiofile.tag.title:
                            music_info.setdefault(
                                "song_name", audiofile.tag.title)
                        music_info.setdefault("artist", audiofile.tag.artist)
                    else:
                        music_info.setdefault(
                            "song_name", os.path.splitext(filename)[0])
                        music_info.setdefault("artist", "")
                    music_info.setdefault("song_id", "0")
                    music_info.setdefault("album_name", "")
                    music_info.setdefault("mp3_url", "'{}'".format(mp3_path))
                    music_info.setdefault("playTime", int(
                        audiofile.info.time_secs) * 1000)
                    music_info.setdefault("quality", "")
                    playlist.append(music_info)
                except Exception, e:
                    self.logger.error(e)
                    pass
            break
        # 随机本地音乐列表顺序
        if 'local_shuffle' in self.profile[SLUG]:
            if self.profile[SLUG]['local_shuffle']:
                shuffle(playlist)
        return playlist

    def get_top_songlist(self):  # 热门单曲
        music_list = self.netease.top_songlist()
        datalist = self.netease.dig_info(music_list, 'songs')
        playlist = []
        for data in datalist:
            music_info = {}
            music_info.setdefault("song_id", data.get("song_id"))
            music_info.setdefault("song_name", data.get("song_name"))
            music_info.setdefault("artist", data.get("artist"))
            music_info.setdefault("album_name", data.get("album_name"))
            music_info.setdefault("mp3_url", data.get("mp3_url"))
            music_info.setdefault("playTime", data.get("playTime"))
            music_info.setdefault("quality", data.get("quality"))
            playlist.append(music_info)
        return playlist

    def read_login_info(self, user_info):
        assert(os.path.exists(user_info))
        with open(user_info) as f:
            self.userId = f.readline()

    def login(self, username, password):  # 用户登陆
        password = hashlib.md5(password).hexdigest()
        login_info = self.netease.login(username, password)
        if login_info['code'] == 200:
            res = True
            userId = login_info.get('profile').get('userId')
            self.userId = userId
            home_dir = os.path.expandvars('$HOME')
            user_info = os.path.join(home_dir, 'userInfo')
            file = open(user_info, 'w')
            file.write(str(userId))
            file.close()
        else:
            res = False
        return res

    def get_user_playlist(self):  # 获取用户歌单
        play_list = self.netease.user_playlist(self.userId)  # 用户歌单
        return play_list

    def get_song_list_by_playlist_id(self, playlist_id):
        songs = self.netease.playlist_detail(playlist_id)
        song_list = self.netease.dig_info(songs, 'songs')
        return song_list

    def search_by_name(self, song_name):
        data = self.netease.search(song_name)
        song_ids = []
        if 'songs' in data['result']:
            if 'mp3Url' in data['result']['songs']:
                songs = data['result']['songs']

            else:
                for i in range(0, len(data['result']['songs'])):
                    song_ids.append(data['result']['songs'][i]['id'])
                songs = self.netease.songs_detail(song_ids)
        song_list = self.netease.dig_info(songs, 'songs')
        return song_list

    def current_song(self):
        if self.song is not None:
            return self.song['song_name']
        else:
            return ''

    def run(self):
        while True:
            if self.cond.acquire():
                self.play()
                self.pick_next()

    def play(self, report=False):
        if self.is_pause:
            self.is_pause = False
        if self.idx < len(self.playlist):
            if self.idx == -1:
                self.idx = 0
            if not self.random:
                song = self.playlist[self.idx]
            else:
                song = random.choice(self.playlist)
            self.song = song
            subprocess.Popen("pkill play", shell=True)
            # pr = cProfile.Profile()
            # pr.enable()
            # if song['mp3_url'] contains 'http://',
            # means music from internet, not local
            if "http://" in song['mp3_url']:
                song['mp3_url'] = self.netease.songs_detail_new_api(
                    [song['song_id']])[0]['url']            
            # pr.disable()
            # s = StringIO.StringIO()
            # sortby = 'cumulative'
            # ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
            # ps.print_stats()
            # print s.getvalue()
            mp3_url = song['mp3_url']
            if mp3_url is None:
                self.next()
                self.cond.wait()
            try:
                if report:
                    logger.debug(u"即将播放：%s，%s" % (
                        song['artist'], song['song_name']))

                time.sleep(.1)
                subprocess.Popen("play -v %f %s" % (
                    self.volume, mp3_url), shell=True, stdout=subprocess.PIPE)
                self.cond.notify()
                self.cond.wait(int(song.get('playTime')) / 1000)
            except Exception:
                pass
        else:
            try:
                subprocess.Popen("pkill play", shell=True)
                self.cond.notify()
                self.cond.wait()
            except Exception:
                pass

    def notify(self):
        if self.cond.acquire():
            self.cond.notifyAll()
            self.cond.release()

    def previous(self):
        self.idx -= 2
        if self.idx < 0:
            self.idx = len(self.playlist) - 1
        self.notify()

    def pick_next(self):
        self.idx += 1
        if self.idx > len(self.playlist) - 1:
            self.idx = 0

    def next(self):
        self.notify()

    def randomize(self):
        self.random = True
        self.next()

    def serialize(self):
        self.random = False
        self.notify()

    def increase_volume(self):
        self.volume += .1
        if self.volume > 1:
            self.volume = 1
        self.notify()

    def decrease_volume(self):
        self.volume -= .1
        if self.volume < 0:
            self.volume = 0
        self.notify()

    def stop(self):
        try:
            subprocess.Popen("pkill play", shell=True)
            self.cond.notifyAll()
            self.cond.release()
            self.cond.wait()
        except Exception:
            pass

    def pause(self):
        self.is_pause = True
        # 暂不支持断点续播，因此暂停和停止相同处理
        self.stop()

    def exit(self):
        self.is_stop = True
        self.playlist = []
        self.notify()

if __name__ == '__main__':
    main()
